﻿#include "mainframe.h"
#include "ui_mainframe.h"
#include "systemmenu.h"

#include <QFile>
#include <QToolButton>
#include <QButtonGroup>
#include <QStackedWidget>
#include <QVBoxLayout>

MainFrame::MainFrame(QWidget *parent) :
    DragableShadowWidget(parent),
    ui(new Ui::MainFrame(this)),
    m_sysmenu(Q_NULLPTR)
{
    initUI();
    createConnections();
}

MainFrame::~MainFrame()
{
}

void MainFrame::initUI()
{
    resize(900, 650);
    setMinimumWidth(900);

    // 加载界面
    ui->setupUi(this);

    // 加载样式
    QFile qss(":/qss/mainframe");
    qss.open(QIODevice::ReadOnly);
    setStyleSheet(qss.readAll());
    qss.close();

    // 菜单
    // 这里采用setMenu的方法来显示系统菜单.通过计算来定位的方法也可以.
    m_sysmenu = new SystemMenu(this);
    ui->m_sysbtn_menu->setMenu(m_sysmenu);
}

void MainFrame::createConnections()
{
    connect(ui->m_sysbtn_close, SIGNAL(clicked(bool)), this, SLOT(onCloseBtnClicked()));
    connect(ui->m_sysbtn_max, SIGNAL(clicked(bool)), this, SLOT(onMaxBtnClicked()));
    connect(ui->m_sysbtn_restore, SIGNAL(clicked(bool)), this, SLOT(onRestoreBtnClicked()));
    connect(ui->m_sysbtn_min, SIGNAL(clicked(bool)), this, SLOT(onMinBtnClicked()));
    //connect(ui->m_sysbtn_menu, SIGNAL(clicked(bool)), this, SLOT(onSysMenuBtnClicked()));
    connect(ui->m_btn_transmit_list, SIGNAL(clicked(bool)), this, SLOT(onTransmitListBtnClicked()));

    connect(ui->m_bigToolButtons, SIGNAL(buttonToggled(int,bool)),
            this, SLOT(onNavButtonToggled(int, bool)));
}

void MainFrame::onMinBtnClicked()
{
    showMinimized();
}

void MainFrame::onMaxBtnClicked()
{
   ui->m_sysbtn_max->hide();
   ui->m_sysbtn_restore->show();
   showMaximized(); // 要写在最后一起更新
}

void MainFrame::onRestoreBtnClicked()
{
   ui->m_sysbtn_max->show();
   ui->m_sysbtn_restore->hide();
   showNormal(); // 要写在最后一起更新
}

void MainFrame::onCloseBtnClicked()
{
    close();
}

/**
 * @brief 改成了使用setMenu来实现Menu Button.
 */
void MainFrame::onSysMenuBtnClicked()
{
    if (Q_NULLPTR == m_sysmenu)
    {
        m_sysmenu = new SystemMenu(this);
    }

    QWidget *sender_widget = static_cast<QWidget *>(sender());
    QPoint p = sender_widget->rect().bottomLeft();
    m_sysmenu->exec(sender_widget->mapToGlobal(p));
}

void MainFrame::onTransmitListBtnClicked()
{
    switchPage(Ui::MainFrame::PAGE_TRANSMIT_LIST);
}

/**
 * @brief 按钮的作用是导航，所以这里叫NavButton.
 */
void MainFrame::onNavButtonToggled(int index, bool is_checked)
{
    if (is_checked)
    {
        switchPage(index);
    }
}

void MainFrame::switchPage(int page_index)
{
    Q_ASSERT(page_index < ui->m_page_container->count());

    ui->m_page_container->setCurrentIndex(page_index);
}
